<script setup lang="ts">
import { Panel, useVueFlow } from "@vue-flow/core";
import type { FlowExportObject, Node as VFNode } from "@vue-flow/core";

const emits = defineEmits<{
  updatePreSaved: []
  updatePreSavedRev: []
}>()
const flowKey = useSessionStorage<FlowExportObject | null>("saved-flow", null, {
  mergeDefaults: true,
  serializer: {
    read(raw) {
      return superjson.parse(raw);
    },
    write(value) {
      return superjson.stringify(value);
    },
  },
});
const toast = useToast();
const { reset, reload } = useDragAndDrop();
const { nodes, addNodes, dimensions, toObject, fromObject, setInteractive }
  = useVueFlow();
const refSavedOnce = ref(false);
const refSaved = computed(() => {
  return refSavedOnce.value || !!flowKey.value;
});
async function onSave() {
  flowKey.value = toObject();
  // 保存了空
  if (flowKey.value.nodes.length === 0) {
    toast.add({
      title: "请先添加节点",
      id: "5467",
      timeout: 1500,
    });
    return;
  }
  $fetch("/api/flow/record", {
    method: "POST",
    body: { data: flowKey.value },
  }).then((res) => {
    if (res.msg === "ok") 
      refSavedOnce.value = true;
    toast.add({
      title: "保存成功",
      id: "5467",
      timeout: 1500,
    });
    emits("updatePreSaved")
  })
}
const banedClick = ref(false);
const affirmReset = ref<number | undefined>();
function onReset() {
  banedClick.value = true;
  toast.add({
    id: "4782",
    icon: "i-heroicons-exclamation-circle",
    title: "即将重置",
    color: "yellow",
    actions: [
      {
        label: "确认",
        click: () => {
          window.clearTimeout(affirmReset.value);
          affirmReset.value = undefined;
          reset();
          banedClick.value = false;
          emits("updatePreSavedRev")
        },
        color: "yellow",
      },
      {
        label: "取消",
        click: () => {
          window.clearTimeout(affirmReset.value);
          affirmReset.value = undefined;
          banedClick.value = false;
        },
      },
    ],
    callback: () => {
      reset();
      banedClick.value = false;
    },
  });
}
async function onRestore() {
  if (!flowKey.value) {
    const res = await $fetch("/api/flow", {
      method: "GET",
    });
    if (res.msg === "no data") {
      console.warn("no data");
      return;
    }
    else {
      console.log("get flow from server");
      flowKey.value = res.data;
    }
  }

  fromObject(flowKey.value);
  console.log("flowKey.value.nodes", flowKey.value.nodes);
  // reload(flowKey.value.nodes.length);
}
function onAdd() {
  const id = nodes.value.length + 1;

  const newNode: VFNode = {
    id: `random_node-${id}`,
    label: `Node ${id}`,
    position: {
      x: Math.random() * dimensions.value.width,
      y: Math.random() * dimensions.value.height,
    },
  };

  addNodes([newNode]);
}
const [isInteractive, toggleReverse] = useToggle(true);
const onInteractive = () => {
  toggleReverse();
};
watch(isInteractive, () => {
  // 状态更改时重新call
  setInteractive(isInteractive.value);
});

const commentRestore = (flowObj: FlowExportObject) => {
  reset();
  window.setTimeout(() => {
    flowKey.value = flowObj;
    fromObject(flowKey.value);
  }, 500)
};
const commentStore = useMyCommentStore();
commentStore.loadSharedFlowObjFn = commentRestore;
</script>

<template>
  <Panel position="top-right" class="save-restore-controls *:m-1">
    <UButton
      class="reset-dark base-style bg-[#e64343] hover:bg-[#d42e2e] disabled:bg-[#e64343b3] disabled:hover:scale-[unset]"
      :disabled="banedClick"
      @click="onReset"
    >
      重置
    </UButton>
    <UButton
      class="save-dark base-style bg-[#33a6b8] hover:bg-[#84d3dc]"
      @click="onSave"
    >
      保存
    </UButton>
    <UButton
      class="restore-dark base-style bg-[#113285] hover:bg-[#2882ff] disabled:bg-[#113285c8] disabled:hover:scale-[unset]"
      :disabled="!refSaved"
      @click="onRestore"
    >
      加载
    </UButton>
    <UButton
      class="interactive-dark base-style bg-[#6f3381] hover:bg-[#b166cf]"
      @click="onInteractive"
    >
      {{ isInteractive ? "交互模式" : "观察模式" }}
    </UButton>
    <!-- DO? 分享按钮 -->
  </Panel>
</template>

<style scoped lang="postcss">
.base-style {
  @apply text-sm hover:scale-105 disabled:hover:scale-100 duration-300 transition-all ease-in disabled:opacity-40;
}
.reset-dark {
  @apply dark:bg-[#e64343] dark:text-white dark:hover:bg-[#d42e2e] dark:disabled:bg-[#e64343b3];
}
.save-dark {
  @apply dark:bg-[#33a6b8] dark:text-white dark:hover:bg-[#84d3dc];
}
.restore-dark {
  @apply dark:bg-[#113285] dark:text-white dark:hover:bg-[#2882ff] dark:disabled:bg-[#113285c8];
}
.interactive-dark {
  @apply dark:bg-[#6f3381] dark:text-white dark:hover:bg-[#b166cf];
}
/* .save-restore-controls {
  font-size: 12px;
}
.save-restore-controls button {
  margin-left: 5px;
  padding: 5px;
  border-radius: 5px;
  font-weight: 700;
  text-transform: uppercase;
  color: #fff;
  -webkit-box-shadow: 0px 5px 10px 0px rgba(0, 0, 0, 0.3);
  box-shadow: 0 5px 10px #0000004d;
  cursor: pointer;
}
.save-restore-controls button:hover {
  transform: scale(105%);
  transition: 0.25s all ease-in-out;
} */
</style>
